<template>
  <el-dialog
    v-model="visible"
    title="地址管理"
    width="1160"
    align-center
    modal-class="address-manage-dialog"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clickClose"
  >
    <template #header>
      <div style="display: flex; justify-content: space-between">
        <p class="f18">地址管理</p>
        <el-button type="primary" plain @click="clickCreate">新建收货地址</el-button>
      </div>
    </template>
    <div class="address-list" v-if="list.length > 0">
      <el-radio-group v-model="radio" @change="changeDefault">
        <div
          v-for="(item, index) in list"
          :key="item.receivingAddressId"
          @click="selectedObj = item"
          :class="{ active: selectedObj.receivingAddressId === item.receivingAddressId }"
        >
          <el-radio :value="item.receivingAddressId">设为默认收货地址</el-radio>
          <div class="info">
            <header>
              <h3>{{ item.receivingName || "-" }}</h3>
              <p>电话：{{ item.receivingMobile || "-" }}</p>
              <p>地址：{{ item.receivingAreaDetail }} {{ item.receivingAddress }}</p>
            </header>
            <footer>
              <!-- {{ selectedObj.receivingAddressId }}--{{ item.receivingAddressId }} -->
              <el-button
                plain
                @click="
                  () => {
                    currObj = item;
                    clickDel();
                  }
                "
                >删除</el-button
              >
              <el-button
                type="primary"
                plain
                @click="
                  () => {
                    currObj = item;
                    clickUpd();
                  }
                "
                >修改</el-button
              >
            </footer>
          </div>
        </div>
      </el-radio-group>
    </div>
    <div v-else style="display: flex; justify-content: center; width: 100%">
      <el-empty description="暂无数据" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :disabled="JSON.stringify(selectedObj) === '{}'" plain @click="clickClose">取消</el-button>
        <el-button type="primary" :disabled="JSON.stringify(selectedObj) === '{}'" @click="submit">保存</el-button>
      </div>
    </template>

    <!-- 新增、修改弹窗 -->
    <el-dialog
      v-model="dialogVisibleArrOrEdit"
      :title="actionType === 'add' ? '新建收货信息' : '修改收货信息'"
      width="500"
      align-center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <div class="form-wrap">
        <el-form :model="form" ref="formRef" label-width="auto" style="max-width: 600px">
          <el-form-item
            prop="receivingName"
            label="收货人"
            :rules="{ required: true, message: '请输入', trigger: ['blur', 'change'] }"
          >
            <el-input
              v-model="form.receivingName"
              placeholder="请输入"
              maxlength="10"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
          <el-form-item
            prop="receivingMobile"
            label="手机"
            :rules="[
              { required: true, message: '请输入' },
              { pattern: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
          >
            <el-input
              v-model="form.receivingMobile"
              placeholder="请输入"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
          <el-form-item
            prop="receivingAreaIds"
            label="收货地址"
            :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
          >
            <el-cascader
              placeholder="请选择"
              class="pb10"
              ref="cascaderRef"
              v-model="form.receivingAreaIds"
              :options="mapList"
              :props="{
                expandTrigger: 'hover', //次级菜单的展开方式
                label: 'name',
                value: 'id'
              }"
              @change="handleChange"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item
            prop="receivingAddress"
            label="详细地址"
            :rules="{ required: true, message: '请输入', trigger: ['blur', 'change'] }"
          >
            <el-input
              v-model="form.receivingAddress"
              placeholder="请输入"
              maxlength="100"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisibleArrOrEdit = false">取消</el-button>
          <el-button type="primary" @click="submitInfo(actionType)">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getObjKeys, getArrayCombine } from "@/utils";
import { saveTempProduct } from "@/apis/procure/entry";
import { useRoute } from "vue-router";
const route = useRoute();
import china from "@/utils/china.json";
import { getAddressByOrderId, saveCustomerAddress, deleteCustomerAddress, getCustomerAddressList } from "@/apis/procure/outbound";

const visible = ref(false);
const radio = ref("");
const dialogVisibleArrOrEdit = ref(false);
const actionType = ref("add");
const form = ref({});
const formRef = ref();
const mapList = ref(china);
const list = ref([]);
const currObj = ref({});
const selectedObj = ref({}); //选中的地址obj

const emit = defineEmits(["close", "submit"]);
const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isShow: false,
        customerId: null,
        selectedObj: {}
      };
    }
  }
});
watch(
  () => props.optionInfo.isShow,
  async val => {
    visible.value = val;
    if (val) {
      getList();
    }
  },
  { deep: true }
);
watch(
  () => props.optionInfo.selectedObj,
  async val => {
    selectedObj.value = JSON.parse(JSON.stringify(val));
    console.log("默认选中的地址===", selectedObj.value);
  },
  { deep: true }
);
watch(
  () => dialogVisibleArrOrEdit.value,
  val => {
    if (!val) {
      formRef.value.resetFields();
    }
  }
);

const getList = () => {
  if (route.query.deliveryId) {
    getAddressByOrderId({ deliveryId: route.query.deliveryId }).then(res => {
      if (res.code === 200) {
        list.value = res.data;

        const defaultObj = list.value.find(item => item.defaultFlag === 1);
        radio.value = defaultObj?.receivingAddressId || null;
      }
    });
  } else {
    getCustomerAddressList({ customerId: props.optionInfo.customerId }).then(res => {
      if (res.code === 200) {
        list.value = res.data;

        const defaultObj = list.value.find(item => item.defaultFlag === 1);
        radio.value = defaultObj?.receivingAddressId || null;
      }
    });
  }
};

//点击创建
const clickCreate = () => {
  form.value = {};
  actionType.value = "add";
  dialogVisibleArrOrEdit.value = true;
  console.log("打开新建弹窗");
};

//点击修改
const clickUpd = () => {
  actionType.value = "upd";
  form.value = JSON.parse(JSON.stringify(currObj.value));
  form.value.receivingAreaIds = form.value.receivingAreaIds?.split(",").map(Number);
  dialogVisibleArrOrEdit.value = true;
};

//点击删除
const clickDel = () => {
  deleteCustomerAddress({ receivingAddressId: currObj.value.receivingAddressId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
      dialogVisibleArrOrEdit.value = false;

      if (selectedObj.value.receivingAddressId === currObj.value.receivingAddressId) {
        //删除了选中的地址，需要重置一下selectedObj={}
        selectedObj.value = {};
      }
    }
  });
};

//设置默认地址
const changeDefault = val => {
  console.log(909090, val);
  currObj.value = list.value.find(item => item.receivingAddressId === val);
  setDefault(currObj.value);
};
const setDefault = currObj => {
  saveCustomerAddress({
    ...currObj,
    receivingAreaIds: String(currObj.receivingAreaIds),
    defaultFlag: 1
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "设置默认地址成功",
        type: "success"
      });
      getList();
      dialogVisibleArrOrEdit.value = false;
    }
  });
};

//确认新建、修改收货信息
const submitInfo = type => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      if (type === "add") {
        // 添加
        const _form = JSON.parse(JSON.stringify(form.value));
        saveCustomerAddress({
          ..._form,
          receivingAreaIds: String(_form.receivingAreaIds),
          defaultFlag: 0,
          customerId: props.optionInfo.customerId
        }).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: "地址创建成功",
              type: "success"
            });
            getList();
            dialogVisibleArrOrEdit.value = false;
          }
        });
      } else {
        // 修改
        const _form = JSON.parse(JSON.stringify(form.value));
        saveCustomerAddress({ ..._form, receivingAreaIds: String(_form.receivingAreaIds) }).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: "仓库修改成功",
              type: "success"
            });
            getList();
            dialogVisibleArrOrEdit.value = false;
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const submit = () => {
  selectedObj.value = list.value.find(item => item.receivingAddressId === selectedObj.value.receivingAddressId);
  emit("submit", selectedObj.value);
};

const cascaderRef = ref();
const handleChange = value => {
  console.log("producerList", value);
  const nodes = cascaderRef.value.getCheckedNodes();
  console.log("找到了当前选中的节点数据===", nodes);
  form.value.receivingAreaDetail = nodes[0].pathLabels.join("");
};

onMounted(async () => {});

const clickClose = () => {
  emit("close");
};
</script>

<style lang="scss">
.address-manage-dialog {
  .el-dialog {
    padding-bottom: 0 !important;
  }
  .el-dialog__footer {
    margin: 0 -24px;
    padding: 14px 24px;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
  }
}
</style>
<style lang="scss" scoped>
.address-list {
  max-height: 500px;
  overflow-y: auto;
  .active {
    .info {
      border: 2px solid #007dff;
    }
  }
  :deep(.el-radio-group) {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    & > div {
      width: 100%;
      position: relative;
    }
    .el-radio {
      position: absolute;
      bottom: 18px;
      left: 16px;
    }
  }
  .info {
    font-size: 14px;
    line-height: 20px;
    border-radius: 4px;
    border: 1px solid #e5e8ef;
    margin-bottom: 10px;
    header {
      padding: 16px;
      border-bottom: 1px solid #e5e8ef;
      h3 {
        font-size: 14px;
        margin-bottom: 10px;
      }
      p {
        font-size: 12px;
        color: #4e5969;
      }
    }
    footer {
      text-align: right;
      padding: 10px 16px;
    }
  }
}
</style>
